//
//  LGKNoteMainController.m
//  LGKNote
//
//  Created by 刘亚军 on 2023/5/26.
//

#import "LGKNoteMainController.h"
#import "LGKConst.h"
#import <YJBaseModule/YJBTableView.h>
#import "LGKNoteMainCell.h"
#import "LGKNoteMainDataModel.h"
#import "LGKNoteMainCell.h"
#import "LGKNoteMainModel.h"
#import "LGKNoteEditViewController.h"
#import <YJSearchController/YJSearchManager.h>
#import "LGNFilterAlertView.h"
#import "LGNFilterModel.h"
#import "LGKNoteSearchViewController.h"
@interface LGKNoteMainController ()<UITableViewDelegate,UITableViewDataSource,YJBTableViewRefreshDelegate,LGNFilterAlertViewDelegate>
@property (nonatomic,strong) UIImageView *searchImgView;
@property (nonatomic,strong) UILabel *searchTipLab;
@property (nonatomic,strong) UIButton *addBtn;
@property (nonatomic,strong) UIButton *keyPointBtn;
@property (nonatomic,strong) UIButton *filterBtn;
@property (nonatomic,strong) YJBTableView *tableView;
@end

@implementation LGKNoteMainController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.dataModel = [[LGKNoteMainDataModel alloc] initWithOwnController:self];
    self.dataModel.ownTableView = self.tableView;
    self.dataModel.sysID = LGKNoteManager.defaultManager.noteParams.isMyNoteEnter ? @"000" : LGKNoteManager.defaultManager.noteParams.sysID;
    self.marqueeTitle = @"我的笔记";
    self.openDismissEdgeGesEnable = YES;
    [self layoutUI];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.addBtn];
    [self yj_loadGifData];
}
- (void)layoutUI{
    self.yj_loadingViewTopSpace = 38;
    
    [self.view addSubview:self.filterBtn];
    [self.filterBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view).offset(-10);
        make.top.equalTo(self.view).offset(5);
        make.width.height.mas_equalTo(28);
    }];
    BOOL hideFIlter = !LGKNoteManager.defaultManager.noteParams.isMyNoteEnter;
    self.filterBtn.hidden = hideFIlter;
    [self.view addSubview:self.keyPointBtn];
    [self.keyPointBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        if (hideFIlter){
            make.right.equalTo(self.view).offset(-10);
        }else{
            make.right.equalTo(self.filterBtn.mas_left).offset(-10);
        }
        make.centerY.equalTo(self.filterBtn);
        make.width.height.mas_equalTo(28);
    }];
    
    UIView *searchBgView = UIView.new;
    searchBgView.backgroundColor = LG_ColorWithHex(0xF2F2F2);
    [self.view addSubview:searchBgView];
    [searchBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(10);
        make.centerY.equalTo(self.filterBtn);
        make.height.mas_equalTo(28);
        make.right.equalTo(self.keyPointBtn.mas_left).offset(-10);
    }];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(searchClickAcion)];
    [searchBgView addGestureRecognizer:tap];
    [searchBgView yj_clipLayerWithRadius:14 width:0 color:nil];
    [searchBgView addSubview:self.searchImgView];
    [self.searchImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(searchBgView);
        make.left.equalTo(searchBgView).offset(10);
        make.height.width.mas_equalTo(18);
    }];
    [searchBgView addSubview:self.searchTipLab];
    [self.searchTipLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(searchBgView);
        make.left.equalTo(self.searchImgView.mas_right).offset(6);
    }];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.equalTo(self.view);
        make.top.equalTo(searchBgView.mas_bottom).offset(5);
    }];
}
- (void)yj_updateData{
    [self.tableView reloadData];
}
- (void)navBar_leftItemPressed:(UIBarButtonItem *)sender{
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)searchClickAcion{
    LGKNoteSearchViewController *searchResultVC = [[LGKNoteSearchViewController alloc] initWithDataModelName:@"LGKNoteMainDataModel"];
    __weak typeof(self) weakSelf = self;
    searchResultVC.updateBlock = ^{
        if (!IsArrEmpty(weakSelf.dataModel.models)){
            [weakSelf tableViewHeaderDidRefresh];
        }else{
            [weakSelf yj_loadGifData];
        }
    };
    [YJSearchManager defaultManager].searchPlaceholder = self.searchTipLab.text;
    [YJSearchManager defaultManager].searchResultController = searchResultVC;
    [YJSearchManager defaultManager].searchControllerName = NSStringFromClass(self.class);
    [YJSearchManager defaultManager].searchStrBlock = ^(NSString * _Nonnull searchStr) {
        searchResultVC.searchKey = searchStr;
    };
    [[YJSearchManager defaultManager] presentSearchControllerBy:self];
    searchResultVC.navigationController = [YJSearchManager defaultManager].navigationController;
}
- (void)addBtnClickAction{
    LGKNoteEditViewController *editVC =  [[LGKNoteEditViewController alloc] initWithDataModelName:@"LGKNoteEditDataModel"];
    editVC.marqueeTitle = @"新建笔记";
    LGKNoteEditModel *model = [[LGKNoteEditModel alloc] init];
    model.SysID = LGKNoteManager.defaultManager.noteParams.sysID;
    model.ResourceID = LGKNoteManager.defaultManager.noteParams.resourceID;
    model.ResourceName = LGKNoteManager.defaultManager.noteParams.resourceName;
    model.MaterialID = LGKNoteManager.defaultManager.noteParams.materialID;
    model.MaterialName = LGKNoteManager.defaultManager.noteParams.materialName;
    editVC.editModel = model;
    __weak typeof(self) weakSelf = self;
    editVC.updateBlock = ^{
        if (!IsArrEmpty(weakSelf.dataModel.models)){
            [weakSelf tableViewHeaderDidRefresh];
        }else{
            [weakSelf yj_loadGifData];
        }
    };
    [self.navigationController pushViewController:editVC animated:YES];
}
- (void)keyPointBtnClickAction{
    self.keyPointBtn.selected = !self.keyPointBtn.selected;
    self.dataModel.resType = self.keyPointBtn.selected ? @"1" : @"";
    [self yj_loadGifData];
}
- (void)filterBtnClickAction{
    LGKNoteMainDataModel *dm = (LGKNoteMainDataModel *)self.dataModel;
    __weak typeof(self) weakSelf = self;
    if (IsArrEmpty(dm.filterModels)){[LGAlert showIndeterminate];};
    [dm getFilterParamsWithCompletion:^(BOOL isOk) {
        if (isOk){
            [LGAlert hide];
            LGNFilterAlertView *alertView = [LGNFilterAlertView filterAlertViewOnView:weakSelf.navigationController.view];
            alertView.delegate = weakSelf;
            alertView.dataArr = dm.filterModels;
            [alertView show];
        }else{
            [LGAlert showErrorWithStatus:@"获取筛选信息失败"];
        }
    }];
   
}
#pragma mark - LGNFilterAlertViewDelegate
- (void)LGNFilterAlertViewDidSelcetedItemAtIndexArr:(NSArray *)indexArr{
    LGKNoteMainDataModel *dm = (LGKNoteMainDataModel *)self.dataModel;
    for (int i = 0; i < indexArr.count; i++) {
        LGNFilterModel *model = dm.filterModels[i];
        NSInteger selIndex = [indexArr[i] integerValue];
        if (i == 0) {
            self.dataModel.sysID = model.SelIDs[selIndex];
        }
    }
    self.filterBtn.selected = ![kApiParams(self.dataModel.sysID) isEqualToString:@"000"];
    [self yj_loadGifData];
}
#pragma mark - YJBTableViewRefreshDelegate
- (void)tableViewHeaderDidRefresh{
    [self.dataModel yj_loadTableFirstPage];
}
- (void)tableViewFooterDidRefresh{
    [self.dataModel yj_loadTableNextPage];
}
#pragma mark - UITableViewDelegate,UITableViewDataSource
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleDelete;
}
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"删除";
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    [LGAlert showIndeterminate];
    LGKNoteMainModel *model = self.dataModel.models[indexPath.row];
    __weak typeof(self) weakSelf = self;
    [(LGKNoteMainDataModel *)self.dataModel removeNoteWithNoteID:model.NoteID completion:^(BOOL isOk) {
        if (isOk){
            [LGAlert showSuccessWithStatus:@"删除成功"];
            NSMutableArray *arr = [NSMutableArray arrayWithArray:weakSelf.dataModel.models];
            [arr removeObject:model];
            if (arr.count == 0){
                [weakSelf yj_setNoDataViewShow:YES];
            }else{
                weakSelf.dataModel.models = arr;
                [weakSelf.tableView reloadData];
            }
        }else{
            [LGAlert showErrorWithStatus:@"删除失败"];
        }
    }];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataModel.models.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    LGKNoteMainCell *cell = nil;
    LGKNoteMainModel *model = self.dataModel.models[indexPath.row];
    if (model.mixTextImage){
        cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(LGKNoteMainTextImgCell.class) forIndexPath:indexPath];
    }else{
        if (!IsArrEmpty(model.imgUrlArr)){
            cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(LGKNoteMainImgCell.class) forIndexPath:indexPath];
        }else{
            cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(LGKNoteMainTextCell.class) forIndexPath:indexPath];
        }
    }
    cell.mainModel = model;
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    LGKNoteMainModel *model = self.dataModel.models[indexPath.row];
    LGKNoteEditViewController *editVC =  [[LGKNoteEditViewController alloc] initWithDataModelName:@"LGKNoteEditDataModel"];
    editVC.marqueeTitle = @"编辑笔记";
    editVC.dataModel.resID = model.NoteID;
    __weak typeof(self) weakSelf = self;
    editVC.updateBlock = ^{
        if (!IsArrEmpty(weakSelf.dataModel.models)){
            [weakSelf tableViewHeaderDidRefresh];
        }else{
            [weakSelf yj_loadGifData];
        }
    };
    [self.navigationController pushViewController:editVC animated:YES];
}
#pragma mark - lazy
- (UILabel *)searchTipLab{
    if (!_searchTipLab){
        _searchTipLab = [UILabel new];
        _searchTipLab.text = @"请输入笔记标题关键字搜索";
        _searchTipLab.textColor = LG_ColorWithHex(0x999999);
        _searchTipLab.font = LG_SysFont(15);
    }
    return _searchTipLab;
}
- (UIImageView *)searchImgView{
    if (!_searchImgView){
        _searchImgView = [[UIImageView alloc] initWithImage:[UIImage yj_imageNamed:@"lg_Newsearch" atBundle:LGKNoteManager.defaultManager.noteBundle]];
    }
    return _searchImgView;
}
- (UIButton *)addBtn{
    if(!_addBtn){
        _addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _addBtn.frame = CGRectMake(0, 0, 28, 28);
        [_addBtn setImage:[UIImage yj_imageNamed:@"note_add" atBundle:LGKNoteManager.defaultManager.noteBundle] forState:UIControlStateNormal];
        [_addBtn addTarget:self action:@selector(addBtnClickAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _addBtn;
}
- (UIButton *)keyPointBtn{
    if (!_keyPointBtn){
        _keyPointBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_keyPointBtn setImage:[UIImage yj_imageNamed:@"note_remark_unselected" atBundle:LGKNoteManager.defaultManager.noteBundle] forState:UIControlStateNormal];
        [_keyPointBtn setImage:[UIImage yj_imageNamed:@"note_remark_selected" atBundle:LGKNoteManager.defaultManager.noteBundle] forState:UIControlStateSelected];
        [_keyPointBtn addTarget:self action:@selector(keyPointBtnClickAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _keyPointBtn;
}
- (UIButton *)filterBtn{
    if (!_filterBtn){
        _filterBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_filterBtn setImage:[UIImage yj_imageNamed:@"note_filter" atBundle:LGKNoteManager.defaultManager.noteBundle] forState:UIControlStateNormal];
        [_filterBtn setImage:[UIImage yj_imageNamed:@"note_filter_sel" atBundle:LGKNoteManager.defaultManager.noteBundle] forState:UIControlStateSelected];
        [_filterBtn addTarget:self action:@selector(filterBtnClickAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _filterBtn;
}
- (YJBTableView *)tableView{
    if (!_tableView){
        _tableView = [[YJBTableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        [_tableView installRefreshHeader:YES footer:YES];
        _tableView.backgroundColor = LG_ColorWithHex(0xf7f7f7);
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.estimatedRowHeight = 100;
        _tableView.refreshDelegate = self;
        [_tableView registerClass:[LGKNoteMainTextImgCell class] forCellReuseIdentifier:NSStringFromClass([LGKNoteMainTextImgCell class])];
        [_tableView registerClass:[LGKNoteMainImgCell class] forCellReuseIdentifier:NSStringFromClass([LGKNoteMainImgCell class])];
        [_tableView registerClass:[LGKNoteMainTextCell class] forCellReuseIdentifier:NSStringFromClass([LGKNoteMainTextCell class])];
    }
    return _tableView;
}
@end
